package com.fwx.chatroom.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fwx.chatroom.component.OnlineUserManage;
import com.fwx.chatroom.mapper.MessageMapper;
import com.fwx.chatroom.mapper.MessageSessionMapper;
import com.fwx.chatroom.model.Friend;
import com.fwx.chatroom.model.Message;
import com.fwx.chatroom.model.User;
import com.fwx.chatroom.testWeb.TestWebSocketController;
import com.fwx.chatroom.webSocketApi.MessageRequest;
import com.fwx.chatroom.webSocketApi.MessageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

@Component
public class WebSocketController extends TestWebSocketController {

    @Autowired
    private OnlineUserManage onlineUserManage;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;

    /*建立连接*/
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("[WebSocketAPI] 连接成功！");
        User user = (User) session.getAttributes().get("user");
        if(user == null) {
            return;
        }
        //键值对存起来
        onlineUserManage.online(user.getUserId(),session);
    }

    //收到消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("[WebSocketAPI] 收到消息！！"+message.toString());
        //消息处理，转发，以及消息保存记录.
        //1.先获取当前用户信息，后续进行消息转发
        User user = (User) session.getAttributes().get("user");
        if(user == null) {
            System.out.println("[WebSocketAPI] user == null！！无法进行消息转发");
            return;
        }
        //针对请求解析数据
        System.out.println(message.getPayload());
        System.out.println(message);
        MessageRequest req = objectMapper.readValue(message.getPayload(), MessageRequest.class);
        if(req.getType().equals("message")) {
            //进行消息转发
            transferMessage(user,req);
        }else {
            System.out.println("[WebSocketAPI] req.type有误" + message.getPayload());
        }

    }

    //完成消息实际转发

    /**
     *
     * @param fromUser 转发消息来种子于谁
     * @param req
     */
    private void transferMessage(User fromUser, MessageRequest req) throws IOException {
        //1.先构造要转发的对象
        MessageResponse resp = new MessageResponse();
        resp.setType("message");
        resp.setFromId(fromUser.getUserId());
        resp.setFromName(fromUser.getUsername());
        resp.setSessionId(req.getSessionId());
        resp.setContent(req.getContent());
        //java对象转换成json字符串
        String respJson = objectMapper.writeValueAsString(resp);
        //2.根据请求的sessionId，获取到MessageSession里的用户,查询数据库获取
       List<Friend> friends = messageSessionMapper.getFriendsBySessionId(resp.getSessionId(), fromUser.getUserId());
        //将消息给自己发送一份
        Friend myself = new Friend();
        myself.setFriendId(fromUser.getUserId());
        myself.setFriendName(fromUser.getUsername());
        friends.add(myself);
        //3.循环遍历列表，给对应用户发送一份响应信息
        for(Friend friend : friends) {
           WebSocketSession webSocketSession = onlineUserManage.getSession(friend.getFriendId());
           if(webSocketSession == null) {
               //如果该用户不在线，则不发送
               continue;
           }
           webSocketSession.sendMessage(new TextMessage(respJson));
        }
        //4.消息入库
        //需要向message表中写入记录
        Message message = new Message();
        message.setFromId(fromUser.getUserId());
        message.setSessionId(req.getSessionId());
        message.setContent(req.getContent());
        messageMapper.add(message);
    }

    //连接异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("[WebSocketAPI] 连接异常！"+exception.toString());

        User user = (User) session.getAttributes().get("user");
        if(user == null) {
            return;
        }
        onlineUserManage.offerline(user.getUserId(),session);
    }

    //断开连接
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("[WebSocketAPI] 断开连接！"+status.toString());

        User user = (User) session.getAttributes().get("user");
        if(user == null) {
            return;
        }
        onlineUserManage.offerline(user.getUserId(),session);
    }
}
